<template>
  <div>
    <!-- 抽屉 -->
    <el-drawer
      title="发布文章到 WordPress"
      :visible.sync="dialogVisible"
      direction="rtl"
      size="90%"
      :modal="false"
      class="full-screen-drawer"
      @close="close"
    >
      <!-- 步骤控制按钮放在顶部 -->
      <div class="steps-action top-actions">
        <el-button v-if="activeStep > 0" class="step-button" @click="prevStep">上一步</el-button>
        <el-button
          v-if="activeStep < 4"
          type="primary"
          :disabled="isNextDisabled"
          class="step-button"
          @click="nextStep"
        >
          下一步
        </el-button>
        <el-button
          v-else
          type="success"
          :loading="publishloading"
          class="step-button"
          @click="handlePublichPost"
        >
          直接发布到该网站
        </el-button>
      </div>

      <!-- 步骤条 -->
      <el-steps :active="activeStep" finish-status="success" align-center>
        <el-step title="选择网站" />
        <el-step title="选择目录" />
        <el-step title="设置标签" />
        <el-step title="设置FeatureImage (可选)" />
        <el-step title="确认发布" />
      </el-steps>

      <!-- 步骤内容 -->
      <div class="steps-content fixed-height">
        <!-- 第一步：选择网站 -->
        <div v-show="activeStep === 0" class="step-pane">
          <h3>选择网站</h3>
          <el-select
            v-model="selected_webs"
            size="mini"
            placeholder="输入域名搜索 WordPress 账户"
            clearable
            filterable
            :remote-method="remoteSearchWebsite"
            remote
            :loading="websLoading"
            style="width: 90%;"
            @change="handleSelectChange"
          >
            <el-option
              v-for="web in webs"
              :key="web.id"
              :label="web.domain + '|今日发帖:' + web.today_post + '|每日限额:' + web.daily_post"
              :value="web.id"
            />
          </el-select>
        </div>

        <!-- 第二步：选择目录 -->
        <div v-show="activeStep === 1" class="step-pane">
          <h3>选择网站目录</h3>
          <wpcategory
            :account_id="selected_webs"
            :show-checkbox="true"
            @handleCheckChange="handleCategoryCheckChange"
          />
        </div>

        <!-- 第三步：设置标签 -->
        <div v-show="activeStep === 2" class="step-pane">
          <h3>设置文章标签 (TAG)</h3>
          <el-tag
            v-for="tag in post_data.dynamicTags"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
        </div>

        <!-- 第四步：设置特色图片 -->
        <div v-show="activeStep === 3" class="step-pane">
          <h3>设置FeatureImage (可选)</h3>
          <wpattachment
            :imagesurls="imagesurls"
            :account_id="selected_webs"
            :article-content="articleContent"
            :article-title="articleTitle"
            :post-id="post_id"
            @wpattachmentSelectChange="wpattachmentSelectChange"
          />
        </div>

        <!-- 第五步：确认发布 -->
        <div v-show="activeStep === 4" class="step-pane">
          <h3>确认发布</h3>
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>发布信息概览</span>
            </div>
            <div class="text item">
              <p><strong>选择的网站：</strong> {{ selectedWebInfo.domain || '未选择网站' }}</p>
            </div>
            <div class="text item">
              <p><strong>选择的目录：</strong>
                <el-tag
                  v-for="category in post_data.categories"
                  :key="category.id"
                  type="info"
                  class="confirmation-tag"
                >
                  {{ category.name }}
                </el-tag>
              </p>
            </div>
            <div class="text item">
              <p><strong>文章标签 (TAG)：</strong>
                <el-tag
                  v-for="tag in post_data.dynamicTags"
                  :key="tag"
                  type="success"
                  class="confirmation-tag"
                >
                  {{ tag }}
                </el-tag>
              </p>
            </div>
            <div class="text item">
              <p><strong>特色图片：</strong></p>
              <div v-if="post_data.wpattachment_id">
                <el-image :src="selectedImageUrl" style="width: 200px; height: auto;" />
              </div>
              <div v-else>未选择特色图片</div>
            </div>
          </el-card>
          <el-alert
            v-if="postlink.length"
            :title="postlink"
            type="success"
            class="mt-2"
          />
          <a v-if="postlink" :href="postlink" target="_blank">打开链接</a>
        </div>
      </div>
    </el-drawer>

    <!-- 选择发送时间的对话框 -->
    <el-dialog
      title="选择发送时间"
      :visible.sync="lateSenddialogVisible"
      width="30%"
    >
      <div>
        <el-date-picker
          v-model="send_date"
          align="right"
          type="datetime"
          value-format="timestamp"
          placeholder="选择日期"
          :picker-options="pickerOptions"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="lateSenddialogVisible = false">取消</el-button>
        <!--        <el-button type="primary" @click="doSendPostLater">确定</el-button>-->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import wpaccount from '@/views/cms/elements/wpaccount'
import { Get as GetWpAccounts } from '@/api/cms/wpaccount'
import wpcategory from '@/views/cms/elements/wpcategory'
import wpattachment from '@/views/cms/elements/wpattachment'
import { Post as PromotePost } from '@/api/cms/wppost'
import { Get as GetPost } from '@/api/cms/post'
import qs from 'qs'
import Cookies from 'js-cookie'

const selected_webs_key = 'pm_selected_web_id'
const selected_webs_query_Key = 'pm_web_search_key'

export default {
  name: 'Wppromote',
  components: { wpaccount, wpcategory, wpattachment },
  props: ['promoteVisiable', 'project_id', 'post_id', 'tags', 'web', 'imagesurls'],
  data() {
    return {
      activeStep: 0, // 当前步骤
      isNextDisabled: true, // 下一步按钮是否禁用
      lateSenddialogVisible: false,
      send_date: '',
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '7天后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }, {
          text: '15天后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 15)
            picker.$emit('pick', date)
          }
        }]
      },
      webs: [],
      selected_webs: null, // 修改为 null，便于类型一致性
      selectedWebInfo: {}, // 保存选中的网站信息
      selectedImageUrl: '', // 保存选中的图片URL
      websLoading: false,
      dialogVisible: false,
      inputVisible: false,
      inputValue: '',
      publishloading: false,
      postlink: '',
      post_data: {
        post_id: '',
        dynamicTags: [],
        feature_image_url: '',
        categories: [],
        wpattachment_id: '',
        account_id: ''
      },
      articleContent: '', // 文章内容
      articleTitle: '' // 文章标题
    }
  },
  watch: {
    tags(v) {
      this.post_data.dynamicTags = v
    },
    web(v) {
      if (v) {
        this.selected_webs = Number(v)
        this.remoteSearchWebsite(v)
      }
    },
    promoteVisiable(v) {
      this.dialogVisible = v
      const storedWebId = Cookies.get(selected_webs_key) || ''
      if (storedWebId) {
        this.selected_webs = Number(storedWebId)
        this.remoteSearchWebsite(this.selected_webs)
      }
      this.handleSelectChange()

      // 当对话框打开时，如果有post_id，获取文章内容
      if (v && this.post_id) {
        this.fetchArticleContent()
      }
    },
    post_id(v) {
      // 当post_id变化时，获取文章内容
      if (v) {
        this.fetchArticleContent()
      }
    }
  },
  created() {
    this.checkNextDisabled()
  },
  methods: {
    remoteSearchWebsite(query) {
      if (query !== '') {
        this.websLoading = true
        Cookies.set(selected_webs_query_Key, query)
        GetWpAccounts(null, qs.stringify({
          kw: query,
          pagesize: 5,
          page: 1
        })).then(response => {
          this.webs = response.data.data.map(v => ({
            id: Number(v.id),
            domain: v.domain,
            today_post: v.today_post,
            daily_post: v.daily_post,
            label: v.domain
          }))
          this.websLoading = false
          // 如果已有选中的网站，设置 selectedWebInfo
          if (this.selected_webs) {
            this.selectedWebInfo = this.webs.find(web => web.id === this.selected_webs) || {}
          }
        }).catch(() => {
          this.websLoading = false
        })
      } else {
        this.webs = []
        this.websLoading = false
      }
    },
    handleSelectChange() {
      if (this.selected_webs) {
        this.selected_webs = Number(this.selected_webs) // 确保类型一致
        this.selectedWebInfo = this.webs.find(web => web.id === this.selected_webs) || {}
        // 检查网站的发文限制
        this.confirmWebSelection()
      } else {
        this.postlink = ''
        this.isNextDisabled = true
      }
    },
    confirmWebSelection() {
      this.post_data.account_id = this.selected_webs
      Cookies.set(selected_webs_key, this.selected_webs)
      this.postlink = ''
      this.isNextDisabled = false
      // 现在由用户手动点击"下一步"按钮进入下一步
      // 移除了自动跳转的逻辑
    },

    handleCategoryCheckChange(data) {
      this.post_data.categories = data
      this.isNextDisabled = data.length === 0

      // 如果目录选择完成，自动进入下一步
      if (data.length > 0) {
        this.nextStep()
      }
    },
    handleClose(tag) {
      const index = this.post_data.dynamicTags.indexOf(tag)
      if (index >= 0) {
        this.post_data.dynamicTags.splice(index, 1)
      }
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.post_data.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
      this.isNextDisabled = this.post_data.dynamicTags.length === 0

      // 如果标签设置完成，自动进入下一步
      if (this.post_data.dynamicTags.length > 0) {
        this.nextStep()
      }
    },
    wpattachmentSelectChange(data) {
      this.post_data.wpattachment_id = data.id_attachment
      this.selectedImageUrl = data.link
      this.isNextDisabled = false

      // 移除自动跳转逻辑，让用户手动选择是否进入下一步
      // 特色图片现在为可选项
    },
    nextStep() {
      if (this.activeStep === 0 && !this.selected_webs) {
        this.$message({
          message: '请先选择一个网站',
          type: 'warning'
        })
        return
      }

      if (this.activeStep < 4) {
        this.activeStep++
        this.checkNextDisabled()
      }
    },
    prevStep() {
      if (this.activeStep > 0) {
        this.activeStep--
      }
      this.checkNextDisabled()
    },
    checkNextDisabled() {
      switch (this.activeStep) {
        case 0:
          this.isNextDisabled = !this.selected_webs
          break
        case 1:
          this.isNextDisabled = this.post_data.categories.length === 0
          break
        case 2:
          this.isNextDisabled = this.post_data.dynamicTags.length === 0
          break
        case 3:
          this.isNextDisabled = false // FeatureImage设置为可选
          break
        default:
          this.isNextDisabled = false
      }
    },
    handlePublichPost() {
      this.post_data.post_id = this.post_id
      this.publishloading = true
      delete this.post_data.send_later
      delete this.post_data.send_date
      PromotePost(this.post_data)
        .then(response => {
          this.postlink = response.data.link
          this.post_data.post_link = this.postlink
          this.$emit('save', this.post_data)
          this.publishloading = false
          this.notify('发布成功')
        })
        .catch(() => {
          this.publishloading = false
        })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    close() {
      this.$emit('closewppromoteDialog')
    },
    async fetchArticleContent() {
      if (!this.post_id) return

      try {
        const response = await GetPost(this.post_id)
        if (response.data && response.data.success) {
          const postData = response.data.data
          this.articleTitle = postData.title || ''
          this.articleContent = postData.content || ''
        }
      } catch (error) {
        console.error('获取文章内容失败:', error)
        // 静默失败，不影响正常功能
      }
    }
  }
}
</script>

<style scoped>
.top-actions {
  display: flex;
  justify-content: center; /* 按钮居中对齐 */
  gap: 15px; /* 按钮之间的间距 */
  margin-bottom: 20px; /* 与步骤条之间的距离 */
}

.steps-content {
  margin-top: 10px;
  padding: 0 40px; /* 左右边距 */
  height: calc(100vh - 240px); /* 动态高度，以适应屏幕大小，考虑按钮和步骤条的高度 */
  overflow-y: auto; /* 当内容超出时滚动 */
}

.step-pane {
  transition: opacity 0.3s ease-in-out; /* 过渡效果，切换步骤更平滑 */
  opacity: 1;
}

.button-new-tag {
  margin-left: 10px;
}

.input-new-tag {
  width: 200px;
  margin-left: 10px;
}

.el-alert {
  margin-top: 20px;
}

.box-card {
  margin-top: 20px;
}

.text.item {
  margin-bottom: 15px;
}

.confirmation-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.mt-2 {
  margin-top: 20px;
}
</style>

